// pages/scankd/scankd.ts
import request from '../../utils/request'
const app = getApp<IAppOption>()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        globalData: {},
        isAuth: false,// 是否授权摄像头
        src: '',// 图片地址

        equipmentNo: '',// 设备号
        xm: '',// 姓名
        sfzNo: '',// 身份证号码
        cs: '',// 出生年月
        nl: '',// 年龄
        ys: '',// 医生账号
        pwd: '',// 医生密码
        rentalDays: '1',// 绑定天数
        phone: '',// 手机号码
        xb: 0,// 性别
        place: '在院',// 就诊地
        bedNo: '',// 床位号
        zd: '',// 诊断

        // 选择卡类型
        showCardType: false,
        cardActions: [
          {
            name: '身份证',
            type: 'idcard',
          },
          {
            name: '社保卡',
            type: 'social_security_card',
          },
        ],
        selectCardType: '',

        // 设备选择框
        showCheckBox: false,
        deviceList: [],

        // 确认框
        popup: {},

        // 电子签名
        showSign: false,
        canvas: '', // Canvas画布
        ctx: "", // Canvas上下文
        pen: 5, // 画笔宽度
        color: "#000", // 画笔颜色
        signFlag: false, // 判断是否有画内容
        signImg: '',// 签名图片地址
        viewSignImg: false,
    },
    startX: 0, // 画布X坐标
    startY: 0, // 画布Y坐标

    // 打开卡选择
    changeCard(){
        this.closeCheckBox()
        this.setData({ showCardType: true });
    },
    // 关闭卡选择
    onClose() {
        this.setData({ showCardType: false });
    },
    // 选中卡片
    onSelect(event: any) {
        let obj = event.detail;
        this.setData({selectCardType: obj.type });
        this.uploadPhoto();
    },

    uploadPhoto() { // 拍摄或从相册选取上传
        let that = this;
        wx.chooseMedia({
            count: 1, // 默认9
            mediaType: ['image'],// 文件类型（只能拍摄图片或从相册选择图片）
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            success(res) {
                let tempFiles = res.tempFiles; // 返回选定照片的本地路径列表 
                that.upload(that, tempFiles);
            }
        })
    },
    upload(page, path) { // 上传图片
        let that = this;
        wx.showToast({ icon: "loading", title: "正在上传……", duration: 30000 });
        wx.uploadFile({
            url: app.globalData.baseUrl + '/applet/images/sfznot', //后端接口
            filePath: path[0].tempFilePath,
            name: 'file',
            formData: {
                diary1: that.data.selectCardType,
            },
            header: {
                'Authorization': app.globalData?.access_token || ''
            },
            success(res) {
                if (res.statusCode == 200) {
                    let data = JSON.parse(res.data);
                    if(data.code == 200) {
                        that.setData({
                            sfzNo: data.data.sfzNo,
                            cs: data.data.cs,
                            xb: data.data.xb,
                            xm: data.data.xm,
                            nl: data.data.nl,
                            phone: data.data.phone,
                        });
                    } else {
                        wx.showModal({ title: '识别出错', content: data.msg, showCancel: false });
                    }
                } else {
                    wx.showToast({
                        title: "识别失败，请稍后重试！",
                        icon: 'none',
                        duration: 1500
                    })
                }
            },
            fail(res) {
                wx.showModal({ title: '提示', content: '上传失败！', showCancel: false });
            },
            complete() {
                wx.hideToast(); //隐藏Toast
            }
        })
    },

    // 加载绑定的设备
    getData(){
        let that = this;
        request.get('/applet/bind-info/list?dataType='+app.globalData.dataType).then((res: any) => {
            if(res.data.code === 200) {
                that.setData({
                    deviceList: res.data.data
                }) 
            }
        })
    },
    // 打开/关闭设备号选项框
    openCheckBox(){
        this.setData({ showCheckBox: !this.data.showCheckBox });
    },
    closeCheckBox(){
        this.setData({ showCheckBox: false });
    },
    haldCheckDevice(e : any){
        let equipmentNo = e.currentTarget.dataset.no
        this.setData({ 
            equipmentNo: equipmentNo,
            showCheckBox: false,
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(e: any) {
        const _this = this
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.camera']) {
                    // 用户已经授权
                    _this.setData({
                        isAuth: true
                    })
                } else {
                    // 用户还没有授权，向用户发起授权请求
                    wx.authorize({
                        scope: 'scope.camera',
                        success() { // 用户同意授权
                            _this.setData({
                                isAuth: true
                            })
                        },
                        fail() { // 用户不同意授权
                            _this.openSetting().then(res => {
                                _this.setData({
                                    isAuth: true
                                })
                            })
                        }
                    })
                }
            },
            fail: res => {
                // 获取用户授权信息失败
            }
        })

        if(e.equipmentNo) {
            _this.setData({
                equipmentNo: e.equipmentNo
            });
        }
    },
    // 打开授权设置界面
    openSetting() {
        const _this = this
        let promise = new Promise((resolve, reject) => {
            wx.showModal({
                title: '授权',
                content: '请先授权获取摄像头权限',
                success(res) {
                    if (res.confirm) {
                        wx.openSetting({
                            success(res) {
                                if (res.authSetting['scope.camera']) { // 用户打开了授权开关
                                    resolve(true)
                                } else { // 用户没有打开授权开关， 继续打开设置页面
                                    _this.openSetting().then(res => {
                                        resolve(true)
                                    })
                                }
                            },
                            fail(res) {
                                
                            }
                        })
                    } else if (res.cancel) {
                        _this.openSetting().then(res => {
                            resolve(true)
                        })
                    }
                }
            })
        })
        return promise;
    },

    takePhoto() {
        const ctx = wx.createCameraContext()
        ctx.takePhoto({
            quality: 'high',
            success: (res) => {
                this.setData({
                    src: res.tempImagePath
                })
                wx.previewImage({
                    current: res.tempImagePath, // 当前显示图片的http链接
                    urls: [res.tempImagePath] // 需要预览的图片http链接列表
                })
            }
        })
    },
    // 扫描设备号二维码
    handleScan() {
        this.closeCheckBox()
        wx.scanCode({
            success: (res) => {
                this.setData({
                    equipmentNo: res.result
                })
            }
        })
    },
    // 设备绑定
    handleBtn() {
        this.closeCheckBox()
        const { equipmentNo } = this.data
        const { sfzNo, xb, cs, xm, nl, ys, pwd, rentalDays, phone, place, bedNo, zd, signImg } = this.data

        // 判断参数
        if(!equipmentNo || !xm || !sfzNo || !rentalDays || !ys || !place || (place === '在院' && !bedNo) || 
        (!app.globalData.doctorAccount && !pwd)){
            wx.showToast({
                title: '请完整输入信息',
                icon: 'error',
                duration: 2000
            })
            return ;
        }
        const param = {
            patientName: xm,
            gender: xb,
            identityNumber: sfzNo,
            birthday: cs,
            age: nl,
            phone: phone ? phone : null,
            rentalDays: rentalDays,
            userName: ys,
            userPassword: pwd,
            dataType: app.globalData.dataType,
            equipmentNo: equipmentNo, // 设备编号
            place: place,
            bedNo: place === '在院'?bedNo:'',
            diagnosis: zd,
            signImg: signImg,
        }

        let that = this;
        wx.showLoading({
            title: '请求中...',
        });
        request.post('/applet/patient/data', param).then((res: any) => {
            wx.hideLoading();
                
            // 保存医生账号信息
            app.globalData.doctorAccount = res.data.data
            wx.setStorageSync('doctorAccount', app.globalData.doctorAccount);
            
            that.setData({
                globalData: app.globalData,
                popup: {
                    idx: Math.random(),
                    show: true,
                    title: '提 示',
                    msg: '患者绑定成功！',
                    icon: '../../static/img/smile.png'
                },
                sfzNo: '', 
                xb: 0,
                cs: '',
                xm: '',
                nl: '', 
                ys: app.globalData.doctorAccount, 
                pwd: '',
                rentalDays: '1',
                phone: '',
                equipmentNo: '',
                place: '在院',
                bedNo: '',
                zd: ''
            })
        })
    },

    /**
     * 根据身份证号码查询患者信息
     */
    searchByIdCardNo(){
        if(this.data.sfzNo) {
            let that = this;
            that.setData({
                cs: '',
                xb: 0,
                xm: '',
                nl: '',
                phone: '',
            });
            request.get('/applet/patient/searchByIdCardNo', {idCardNo: this.data.sfzNo}).then((res: any) => {
                let data = res.data.data;
                if(data) {
                    that.setData({
                        sfzNo: data.sfzNo,
                        cs: data.cs,
                        xb: data.xb,
                        xm: data.xm,
                        nl: data.nl,
                        phone: data.phone,
                    });
                }
            });
        } else {
            wx.showToast({
                title: '请先填入身份证号',
                icon: 'error',
                duration: 2000
            })
        }
    },

    openSign(){
        this.setData({
            showSign: true
        });
        // 获取canvas的上下文对象
        const query = wx.createSelectorQuery();
        query.select('#signatureCanvas')
            .fields({ node: true, size: true })
            .exec((res) => {
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');
            
            // 在新版的 canvas 接口中需要显式的设置画布的宽高
            // 一定要手动指定画布的宽高
            // 否则画布会被拉伸
            const dpr = wx.getSystemInfoSync().pixelRatio;
            canvas.width = res[0].width * dpr;
            canvas.height = res[0].height * dpr;
            ctx.scale(dpr, dpr);

            this.setData({
                canvas: canvas,
                ctx: ctx
            });
        });
    },
    touchstart(e:any) {
        // 拿到手指按下时的坐标
        this.startX = e.changedTouches[0].x;
        this.startY = e.changedTouches[0].y;

        // 进行一些绘制的准备工作（笔粗细、颜色、笔头）
        this.data.ctx.lineWidth = this.data.pen; // 笔粗细
        this.data.ctx.strokeStyle = this.data.color; // 画笔颜色
        this.data.ctx.lineCap = 'round'; // 设置笔头

        // 开始绘制
        this.data.ctx.beginPath();
    },
    touchmove(e:any) {
        // 移动的时候，得到的实时的坐标
        var startX1 = e.changedTouches[0].x;
        var startY1 = e.changedTouches[0].y;
        // 首先将画笔移动到手指按下的地方
        this.data.ctx.moveTo(this.startX, this.startY);
        // 描线，根据实时的坐标进行进行描线
        this.data.ctx.lineTo(startX1, startY1);
        // 绘制直线
        this.data.ctx.stroke();

        // 注意，这个步骤也很重要，需要更新起始坐标
        this.startX = startX1;
        this.startY = startY1;

        if(this.startX != 0 && this.startY != 0) {
            this.setData({
                signFlag: true,
            });
        }
    },
    touchend() {
        this.data.ctx.closePath();
    },
    // 清除画布内容
    clearCanvasAll() {
        const ctx = this.data.ctx;
        const canvas = ctx.canvas;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        this.startX = 0;
        this.startY = 0;
        this.setData({
            signFlag: false,
        });
    },
    closeSign(){
        this.setData({
            showSign: false,
            signFlag: false,
        });
    },
    finishSign(){
        let that = this;
        wx.canvasToTempFilePath({
            canvas: that.data.canvas,
            success(res) {
                wx.showToast({ icon: "loading", title: "正在上传……", duration: 30000 });
                wx.uploadFile({
                    url: app.globalData.baseUrl + '/file/upload', //文件上传接口
                    filePath: res.tempFilePath,
                    name: 'file',
                    header: {
                        'Authorization': app.globalData?.access_token || ''
                    },
                    success(res) {
                        if (res.statusCode == 200) {
                            let data = JSON.parse(res.data);
                            if(data.code == 200) {
                                that.setData({
                                    signImg: data.data
                                });
                                that.closeSign();
                            } else {
                                wx.showModal({ title: '提示', content: data.msg, showCancel: false });
                            }
                        } else {
                            wx.showToast({
                                title: "识别失败，请稍后重试！",
                                icon: 'none',
                                duration: 1500
                            })
                        }
                    },
                    fail(res) {
                        wx.showModal({ title: '提示', content: '上传失败！', showCancel: false });
                    },
                    complete() {
                        wx.hideToast(); //隐藏Toast
                    }
                })
            },
            fail(res){
                wx.showToast({
                    title: '生成图片失败！',
                    icon: 'error',
                    duration: 2000
                })
            },
        });
        
    },

    viewSign(){
        this.setData({
            viewSignImg: true
        });
    },
    reSign(){
        this.closeViewSign();

        this.openSign();
    },
    closeViewSign(){
        this.setData({
            viewSignImg: false
        });
    },

    // 加载医生签名
    loadSign(doctorAccount : string){
        let that = this;
        request.get('/applet/bind-info/getDoctorSign?doctor=' + doctorAccount).then((res: any) => {
            if(res.data.code === 200) {
                that.setData({
                    signImg: res.data.data
                });
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            globalData: app.globalData,
            ys: app.globalData.doctorAccount
        });
        
        this.getData();
        if(app.globalData.doctorAccount) {
            this.loadSign(app.globalData.doctorAccount);    
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})